package app;

import items.Category;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/*
 * Writes the item name, date, and prices for each date to a file
 */
public class Writer {
	
	public void writeToFile(Reader reader, Parser parser) throws IOException {
		String location = reader.getLocation();
		String category = reader.getCategory();
		String itemName = reader.getItemName();
		String fileName = todaysDate(location, category);
		BufferedWriter bwFile = new BufferedWriter(new FileWriter(fileName, true));
		ArrayList<String> uList = parser.getUnformattedList();
		
		bwFile.write(itemName);
		bwFile.write('\n');
		
		for (int i = 1; i < uList.size()-1; i=i+2) {
			if (uList.get(i).contains(StrVar.AVG.getVarName())) {
				break;
			}
			else {
				bwFile.write(uList.get(i));
				bwFile.write(",");
				bwFile.write(uList.get(i+1));
				bwFile.write('\n');
			}
		}
		
		bwFile.write('\n');
		bwFile.flush();
		bwFile.close();
	}

	private String todaysDate(String location, String category) {
		Category ct = new Category(category);
		SimpleDateFormat sdf = new SimpleDateFormat(StrVar.FILEDATEFMT.getVarName());
		Date date = new Date();
		StringBuilder today = new StringBuilder(location);
		today.append(sdf.format(date));
		today.append(".");
		today.append(ct.shortNameConvert(category));
		today.append(StrVar.TXT.getVarName());
		return today.toString();
	}
}
